package com.xxg.websocket.server;

import lombok.extern.slf4j.Slf4j;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@ServerEndpoint(value = "/websocket/{user}")
public class MySocketServer {
    /**
     * 在线人数
     */
    public static AtomicInteger onlineNumber = new AtomicInteger(0);

    /**
     * 会话，与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 每个会话的用户
     */
    private String user;
    /**
     * 所有的对象，每次连接建立，都会将我们自己定义的MyWebSocket存放到List中，
     */
    public static List<MySocketServer> webSockets = new CopyOnWriteArrayList<MySocketServer>();


      /**
     　  * 连接建立后触发的方法
     　**/
      @OnOpen
      public void onOpen(Session session, @PathParam("user") String user){
          if (user == null || "".equals(user)) {
              try {
                  session.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return;
          }
          onlineNumber.incrementAndGet();
          for (MySocketServer myWebSocket : webSockets) {
              if (user.equals(myWebSocket.user)) {
                  try {
                      session.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }

                  return;
              }
          }
          this.session = session;
          this.user = user;
          webSockets.add(this);
          System.out.println("有新连接加入！ 当前在线人数" + onlineNumber.get());

   }

    /**
     　　* 连接关闭后触发的方法
     　　*/
    @OnClose
    public void onClose(){
        onlineNumber.decrementAndGet();
        webSockets.remove(this);
        System.out.println("有连接关闭！ 当前在线人数" + onlineNumber.get());
    }
    /**
     　　 * 接收到客户端消息时触发的方法
     　　 */
    @OnMessage
    public void onMessage(String message,Session session,@PathParam("user")String user) throws Exception{
        System.out.println("来自" + user + "消息：" + message);
        pushMessage(user, message, null);
    }


    /**
 　　 * 发生错误时触发的方法
 　　*/
    @OnError
    public void onError(Session session,Throwable error){
        log.info(session.getId()+"连接发生错误"+error.getMessage());
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException{
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void pushMessage(String user, String message, String uuid) throws IOException {
        if (uuid == null || "".equals(uuid)) {
            for (MySocketServer myWebSocket : webSockets) {
                myWebSocket.sendMessage(user + ":" + message);
            }
        } else {
            for (MySocketServer myWebSocket : webSockets) {
                if (uuid.equals(myWebSocket.user)) {
                    myWebSocket.sendMessage(message);
                }
            }
        }
    }

}
